<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Mouse Tracker demo</title>
<style>
.red {
	color:red; font-weight:bold;
}
</style>
<script src="/javascripts/jquery-1.4.4.min.js"></script>
</head>
<body>
エミュレートする遅延時間<input type="text" id=delay value="0" size="3">[msec]<br/>
<div class=red>※遅延時間を変更する際は、上のボックスに数値を入力後、[enter]キーを押してください</div>
<div id=protocol></div>
<div style="width:640px;
	height:320px;
	postion:absolute;
	border:1px solid black"
	id=box></div>
<div id=log></div>
<script type="text/javascript">
var box = document.getElementById('box'),
	log = document.getElementById('log'),
	pEx = document.getElementById('protocol'),
	conn, xhr, protocol, delay = 0;

const pWS=0, pHTTP=1;
protocol = pWS, fSend = false;
pEx.innerHTML = "WebSocket";

$('#delay').change(function(){
	delay = parseInt($(this).val());
	alert('遅延が'+delay+'ミリ秒に変更されました');
	$('#box').empty();
});

var xhr = new XMLHttpRequest();

function sendXHR(x, y){
	xhr.open("get", "http://" + location.host + ":8002/hoge?delay="+delay+"&x="+x+"&y="+y);
	xhr.send();
}

xhr.onload = function(e) {
	fSend = false;
	var ps = JSON.parse(xhr.responseText);
	showTrace([ps.x, ps.y], false);
};

box.onmousemove=function(e) {
	if (protocol == pHTTP) {
		if (xhr && !fSend) {
			fSend = true;
			sendXHR(e.clientX, e.clientY);
		}
	}
	else {
		if (conn && conn.readyState == 1) {
			conn.send(JSON.stringify([e.clientX, e.clientY,delay]));
		}
	}
}

function showTrace(arr, flag){
	flag = typeof(flag) == 'undefined' ? true : flag;
	var mark = document.createElement('div');
	mark.style.position = 'absolute';
	mark.style.width = "10px";
	mark.style.height = "10px";
	mark.style.WebkitBorderRadius = "10px";
	mark.style.MozBorderRadius = "10px";
	mark.style.oBorderRadius = "10px";
	mark.style.BorderRadius = "10px";
	mark.style.border = "1px solid black";
	mark.style.background = flag ? "red" : "blue";
	mark.style.left = arr[0]+"px";
	mark.style.top = arr[1]+"px";
	box.appendChild(mark);
}

// WebSocketサーバーへ接続する
conn = new WebSocket("ws://"+document.location.host+":8002/");
// 接続時のハンドラ
conn.onopen = function(){
  log.innerHTML = "connected";
}

// メッセージを受信時のハンドラ
conn.onmessage = function(e) {
	showTrace(JSON.parse(e.data));
};

// 切断時のハンドラ
conn.onclose = function() {
	log.innerHTML = "disconnected";
};

setInterval(function(){
	if (protocol == pWS) {
		protocol = pHTTP;
		pEx.innerHTML = "HTTP";
	} else {
		protocol = pWS;
		pEx.innerHTML = "WebSocket";
	}
}, 5000);
</script>
</body>
</html>
